package com.older.wptsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.older.wptsb.domain.dto.AlertLogDTO;
import com.older.wptsb.domain.dto.CommunityContactDTO;
import com.older.wptsb.domain.dto.CommunityDTO;
import com.older.wptsb.domain.dto.UpdateCommunityDTO;
import com.older.wptsb.domain.po.AlertLog;
import com.older.wptsb.domain.po.Community;
import com.older.wptsb.domain.po.CommunityContact;
import com.older.wptsb.domain.po.User;
import com.older.wptsb.domain.vo.AlertLogVO;
import com.older.wptsb.domain.vo.CommunityContactVO;
import com.older.wptsb.domain.vo.CommunityVO;
import com.older.wptsb.domain.vo.MyCommunityVO;
import com.older.wptsb.exception.CommunityException;
import com.older.wptsb.mapper.AlertLogMapper;
import com.older.wptsb.mapper.CommunityContactMapper;
import com.older.wptsb.mapper.CommunityMapper;
import com.older.wptsb.mapper.UserMapper;
import com.older.wptsb.service.CommunityService;
import com.older.wptsb.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements CommunityService {
    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AlertLogMapper alertLogMapper;
    @Autowired
    private CommunityContactMapper communityContactMapper;

    // 获取社区列表
    @Override
    public List<CommunityVO> getCommunityList() {
        List<Community> communities = communityMapper.selectList(null);
        return communities.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    // 获取社区信息
    @Override
    public CommunityVO getCommunity(Integer id) {
        Community community = communityMapper.selectById(id);
        return CommunityVO.builder()
                .communityId(community.getCommunityId())
                .name(community.getName())
                .address(community.getAddress())
                .contactPerson(community.getContactPerson())
                .contactPhone(community.getContactPhone())
                .description(community.getDescription())
                .announcement(community.getAnnouncement())
                .elderCount(community.getElderCount())
                .status(community.getStatus())
                .build();
    }
    // 更新社区信息
    @Override
    public void updateCommunity(CommunityDTO communityDTO) {
        communityMapper.update(Community.builder()
                .communityId(communityDTO.getCommunityId())
                .name(communityDTO.getName())
                .address(communityDTO.getAddress())
                .contactPerson(communityDTO.getContactPerson())
                .contactPhone(communityDTO.getContactPhone())
                .description(communityDTO.getDescription())
                .description_photo("")
                .announcement(communityDTO.getAnnouncement())
                .announcement_photo("")
                .elderCount(communityDTO.getElderCount())
                .status(communityDTO.getStatus())
                .build(), new QueryWrapper<Community>().eq( "community_id", communityDTO.getCommunityId())
        );



    }
    // 添加社区
    @Override
    public void addCommunity(CommunityDTO communityDTO) {
        Community community = communityMapper.selectOne(new QueryWrapper<Community>().eq("name", communityDTO.getName()));
        if (community == null) {
            LocalDateTime now = LocalDateTime.now();
            String formattedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            communityMapper.insert(Community.builder()
                    .name(communityDTO.getName())
                    .address(communityDTO.getAddress())
                    .contactPerson(communityDTO.getContactPerson())
                    .contactPhone(communityDTO.getContactPhone())
                    .description(communityDTO.getDescription())
                    .description_photo("")
                    .elderCount(communityDTO.getElderCount())
                    .announcement(communityDTO.getAnnouncement())
                    .announcement_photo("")
                    .status(communityDTO.getStatus())
                    .createTime(formattedNow)
                    .build());
        }
        else {
            throw new CommunityException("社区已存在");
        }
    }
    // 获取当前用户的社区信息
    @Override
    public MyCommunityVO getMyCommunity() {
        Long userId = UserContext.getUserId();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", userId));
        Community community = communityMapper.selectOne(new QueryWrapper<Community>().eq( "community_id", user.getCommunityId()));
        return MyCommunityVO.builder()
                .communityId(community.getCommunityId())
                .name(community.getName())
                .address(community.getAddress())
                .contactPerson(community.getContactPerson())
                .contactPhone(community.getContactPhone())
                .description(community.getDescription())
                .description_photo(community.getDescription_photo())
                .announcement(community.getAnnouncement())
                .announcement_photo(community.getAnnouncement_photo())
                .elderCount(community.getElderCount())
                .build();
    }

    @Override
    public void decrementElderCount(Integer communityId) {
        this.update(new UpdateWrapper<Community>()
                .eq("community_id", communityId)
                .setSql("elder_count = elder_count - 1"));
    }

    @Override
    public List<AlertLogVO> getAlertLog() {
        Long currentUserId = UserContext.getUserId();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", currentUserId));
        return communityMapper.getAlertLog(user.getCommunityId());

    }

    @Override
    public AlertLogVO getAlertLogById(Integer id) {
        return communityMapper.getAlertLogById(id);
    }

    @Override
    public void updateAlertlog(AlertLogDTO alertLogDTO) {
        LocalDateTime now = LocalDateTime.now();
        String formattedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        alertLogMapper.update(AlertLog.builder()
                .status(alertLogDTO.getStatus())
                .solution(alertLogDTO.getSolution())
                .resolveTime(formattedNow)
                .build(), new QueryWrapper<AlertLog>().eq("alert_id", alertLogDTO.getAlertId()));
    }

    @Override
    public List<CommunityContactVO> getCommunityUser() {
        Long currentUserId = UserContext.getUserId();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", currentUserId));
        return communityMapper.getCommunityUser(user.getCommunityId());
    }

    @Override
    public void addCommunityUser(CommunityContactDTO communityContactDTO) {
        CommunityContact communityContact = communityContactMapper.getCommunityUser1(communityContactDTO.getContactName());
        if (communityContact == null) {
            LocalDateTime now = LocalDateTime.now();
            String formattedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            communityContactMapper.insert(CommunityContact.builder()
                    .communityId(communityContactDTO.getCommunityId())
                    .contactName(communityContactDTO.getContactName())
                    .contactPhone(communityContactDTO.getContactPhone())
                    .contactPosition(communityContactDTO.getContactPosition())
                    .contactEmail(communityContactDTO.getContactEmail())
                    .status(communityContactDTO.getStatus())
                    .createTime(formattedNow)
                    .updateTime(formattedNow)
                    .build());
        }
    }

    @Override
    public void updateCommunityUser(Integer id, CommunityContactDTO communityContactDTO) {
        LocalDateTime now = LocalDateTime.now();
        String formattedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        communityContactMapper.update(CommunityContact.builder()
                .communityId(communityContactDTO.getCommunityId())
                .contactName(communityContactDTO.getContactName())
                .contactPhone(communityContactDTO.getContactPhone())
                .contactPosition(communityContactDTO.getContactPosition())
                .contactEmail(communityContactDTO.getContactEmail())
                .status(communityContactDTO.getStatus())
                .updateTime(formattedNow)
                .build(), new QueryWrapper<CommunityContact>().eq("id", id)
        );

    }

    @Override
    public void deleteCommunityUser(Integer id) {
        communityContactMapper.deleteId(id);
    }

    @Override
    public String getCurrentCommunity() {
        Long currentUserId = UserContext.getUserId();
        System.out.println("当前用户ID：" + currentUserId);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", currentUserId));
        return user.getCommunityId().toString();
    }

    @Override
    public void updateCommunity1(UpdateCommunityDTO updateCommunityDTO) {
        communityMapper.update(Community.builder()
                .name(updateCommunityDTO.getName())
                .address(updateCommunityDTO.getAddress())
                .contactPerson(updateCommunityDTO.getContactPerson())
                .contactPhone(updateCommunityDTO.getContactPhone())
                .description(updateCommunityDTO.getDescription())
                .description_photo(updateCommunityDTO.getDescription_photo())
                .announcement(updateCommunityDTO.getAnnouncement())
                .announcement_photo(updateCommunityDTO.getAnnouncement_photo())
                .build(), new QueryWrapper<Community>().eq("community_id", updateCommunityDTO.getCommunityId())
        );
    }

    // Community转换CommunityVO
    private CommunityVO convertToVO(Community community) {
        return CommunityVO.builder()
                .communityId(community.getCommunityId())
                .name(community.getName())
                .address(community.getAddress())
                .contactPerson(community.getContactPerson())
                .contactPhone(community.getContactPhone())
                .description(community.getDescription())
                .elderCount(community.getElderCount())
                .status(community.getStatus())
                .createTime(community.getCreateTime())
                .build();
    }
}
